import fs from "fs";
import path from "path";
import { getTagLabel } from "../../util/helper";
const { resolve } = path;

export default (md: any) => {
  const render = md.render;
  md.render = (...args: any[]) => {
    let result = render.call(md, ...args);
    // 匹配demo-block标签
    const demoReg = new RegExp(/<demo-block([\s\S]*?)(<\/demo-block>|\/>)/, "g");
    const demoTagList = result.match(demoReg);

    // 遍历匹配到的demo-block标签
    demoTagList?.forEach(async (tagText: any) => {
      // 获取demo-block标签的src属性
      const src = getTagLabel(tagText, "demo-block", "src");
      // 读取src属性对应的文件内容
      const codeString = fs.readFileSync(resolve(`./src/${src}.vue`)).toString();
      // 将demo-block标签替换为带有codeString属性的标签
      const demoStr = tagText.replace(">", ` codeString="${encodeURIComponent(codeString)}">`);
      // 将匹配到的demo-block标签替换为带有codeString属性的标签
      result = result.replace(tagText, demoStr);
    });
    return result;
  };
};
